package net.sansi.v3correctserver.service.correctresult;

import cn.hutool.core.util.ZipUtil;
import net.sansi.v3correctserver.config.matrixloader.DoubleArrMatrixFileLoader;
import net.sansi.v3correctserver.constenum.AppHelper;
import net.sansi.v3correctserver.dto.correctresult.CorrectResultDto;
import net.sansi.v3correctserver.entity.screen.Panel;
import net.sansi.v3correctserver.entity.screen.ScanBoard;
import net.sansi.v3correctserver.entity.space.CorrectCnf;
import net.sansi.v3correctserver.exception.ServiceException;
import net.sansi.v3correctserver.service.correctresult.convert.FactorToCFConvert;
import net.sansi.v3correctserver.service.correctresult.convert.FactorToCLConvert;
import net.sansi.v3correctserver.service.screen.ScreenService;
import net.sansi.v3correctserver.service.space.ProjectSpace;
import net.sansi.v3correctserver.task.SolidifyFactorTask;
import net.sansi.v3correctserver.task.UploadFactorTask;
import net.sansi.v3correctserver.util.Matrix;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Fang
 * create time : 2024/11/11
 * IDE : IntelliJ IDEA
 */

@Service
public class CorrectResultService {

    // 矫正结果类型 1. 亮度矫正 2. 色度矫正
    public static final int CORRECT_TYPE_BRIGHTNESS = 1;
    public static final int CORRECT_TYPE_CHROMA = 2;

    // 系数类型 1. 面板 CL 2. 扫描板 CF
    public static final int FACTOR_TYPE_CL = 1;
    public static final int FACTOR_TYPE_CF = 2;

    /**
     * 启动系数上传任务
     *
     * @param form 参数
     * @return 任务id
     */
    public String startUploadFactor(CorrectResultDto.StartUploadFactorReq form) {
        CorrectCnf correctCnf = AppHelper.projectSpace().getCorrectCnf();
        UploadFactorTask task = new UploadFactorTask(form, screenService.scanBoards(correctCnf.getScreenId()));
        AppHelper.getTaskManager().addTask(task, true);
        return task.getTaskId();
    }


    public String startSolidifyFactor(CorrectResultDto.StartSolidifyFactorReq form) {
        CorrectCnf correctCnf = AppHelper.projectSpace().getCorrectCnf();
        SolidifyFactorTask task = new SolidifyFactorTask(form, screenService.scanBoards(correctCnf.getScreenId()));
        AppHelper.getTaskManager().addTask(task, true);
        return task.getTaskId();
    }


    /**
     * 搜索最优结果
     * 1. 色度矫正 + 亮暗线结果
     * 2. 色度矫正
     * 3. 亮度矫正 + 亮暗线结果
     * 4. 亮度矫正
     *
     * @return 矫正结果路径
     */
    public Path findMustNiceResult() {
        // TODO 搜索最优结果
        return null;
    }

    @Resource
    private ScreenService screenService;

    /**
     * 生成系数文件
     *
     * @param form 参数
     * @return 参数
     */
    public String genFactor(CorrectResultDto.GenFactorReq form) {
        ProjectSpace projectSpace = AppHelper.projectSpace();
        CorrectCnf correctCnf = projectSpace.getCorrectCnf();
        List<Matrix<double[]>> results = loadResult(form.getCorrectType(), form.getFixLine());
        List<ScanBoard> scanBoards = screenService.scanBoards(correctCnf.getScreenId());
        if (scanBoards.isEmpty()) throw new ServiceException("扫描板不存在");
        Path savePath = form.getFactorType() == FACTOR_TYPE_CF ?
                projectSpace.factorCFZip() : projectSpace.factorCLZip();
        List<File> files = new ArrayList<>();
        for (ScanBoard scanBoard : scanBoards) {
            if (form.getFactorType() == FACTOR_TYPE_CF) {
                Path path = new FactorToCFConvert(scanBoard, results, form.getIs3Factor(), projectSpace)
                        .convertAndSave();
                files.add(path.toFile());
            } else if (form.getFactorType() == FACTOR_TYPE_CL) {
                for (Panel panel : scanBoard.getPanels()) {
                    Path path = new FactorToCLConvert(panel, results, form.getIs3Factor(), projectSpace)
                            .convertAndSave();
                    files.add(path.toFile());
                }
            }
        }
        ZipUtil.zip(savePath.toFile(), false, files.toArray(new File[0]));
        if (!form.getIsUpload()) return "success";
        return startUploadFactor(new CorrectResultDto.StartUploadFactorReq()
                .setFactorType(form.getFactorType())
        );
    }

    /**
     * 加载结果
     *
     * @param correctType 类型 1. 亮度矫正 2. 色度矫正
     * @param fixLine     是否修复亮暗线
     * @return 结果 [ r, g, b ]
     */
    public List<Matrix<double[]>> loadResult(int correctType, boolean fixLine) {
        ProjectSpace projectSpace = AppHelper.projectSpace();
        List<Matrix<double[]>> results = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Path path = projectSpace.brightMergeResult(i, fixLine);
            if (correctType == CORRECT_TYPE_CHROMA) {
                // TODO 获取色度文件路径用来加载色度结果
            }
            if (!path.toFile().exists()) {
                throw new ServiceException("结果文件不存在 {}", path.toAbsolutePath());
            }
            results.add(Matrix.load(new DoubleArrMatrixFileLoader(3), path));
        }
        return results;
    }

}
